package ru.sgu.diploma.practic.utils;

import ru.sgu.diploma.practic.domain.model.ApplicationOption;
import ru.sgu.diploma.practic.errors.ApplicationConfigurationException;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;

/**
 * User: datmakin
 * Date: 15.03.11
 * Email: atmakin.dv@gmail.com
 */
public class ConfiguratorUtils {

    public static Integer findMod(String[] args) {
        return findInteger(ApplicationOption.MOD, args);
    }

    public static Integer findScale(String[] args) {
        return findInteger(ApplicationOption.SCALE, args);
    }

    public static Integer findLength(String[] args) {
        return findInteger(ApplicationOption.LENGTH, args);
    }

    public static String findName(String args[]) {
        for (int i = 0; i < args.length; i++) {
            if (args[i].equals("-" + ApplicationOption.PATH.getFlag()) && (i + 1) < args.length) {
                String path = args[i + 1];
                File file = new File(path);
                return file.getName();
            }
        }
        return "test";
    }

    public static BufferedReader findPath(String args[]) throws ApplicationConfigurationException {

        for (int i = 0; i < args.length; i++) {
            if (args[i].equals("-" + ApplicationOption.PATH.getFlag()) && (i + 1) < args.length) {
                String path = args[i + 1];
                File file = new File(path);
                try {
                    FileReader reader = new FileReader(file);
                    BufferedReader buffer = new BufferedReader(reader);
                    return buffer;
                } catch (FileNotFoundException e) {
                    throw new ApplicationConfigurationException(path + " - file not found.");
                }
            }
        }

        throw new ApplicationConfigurationException("path not found in command options");
    }

    private static Integer findInteger(ApplicationOption option, String[] args) {
        try {
            for (int i = 0; i < args.length; i++) {
                if (args[i].equals("-" + option.getFlag()) && (i + 1) < args.length) {
                    Integer lenght = Integer.parseInt(args[i + 1]);
                    return lenght;
                }
            }
        } catch (Exception e) {
            return Integer.parseInt(option.getDefaultValue());
        }
        return Integer.parseInt(option.getDefaultValue());
    }

    public static Integer findMAXN(String args[]) {
        return findInteger(ApplicationOption.MAXN, args);
    }
}
